package com.jason.campusinn;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;

import com.jason.campusinn.constants.Constants;
import com.jason.campusinn.service.CampusInnService;
import com.lidroid.xutils.DbUtils;
import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

public class CampusInnApp extends Application {
    private static List<Activity> activitys = null;
    public static CampusInnApp instance;
    /**
     * 友盟统计开关
     */
    public static boolean isUmengStarted = false;
    /**
     * 屏幕宽度
     */
    public int mScreenWidth;

    /**
     * 屏幕高度
     */
    public static int mScreenHeight;
    /**
     * 屏幕密度
     */
    public float mScreenDensity;
    /**
     * 字体缩放比例
     */
    public float mScaledDensity;
    /**
     * 状态栏高度
     */
    public int mStatusBarHeight;
    public static DbUtils dbUtils;
//    public static Typeface mFontTypefaceLight;
//    public static Typeface mFontTypefaceMedium;
//    public static Typeface mFontTypefaceNormal;

    //计时器
    private long timer;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        initDbutils();
        getDisplayMetrics();
        startService(new Intent(getApplicationContext(),CampusInnService.class));
        deviceInformation();
        activitys = new LinkedList<Activity>();

    }

    private void deviceInformation() {
        Log.d(getApplicationInfo().packageName, "手机型号: \n"
                + android.os.Build.MODEL + ",\nSDK版本:"
                + android.os.Build.VERSION.SDK + ",\n系统版本:"
                + android.os.Build.VERSION.RELEASE);
    }

    /**
     * 获得当前进程号
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }


    private void getDisplayMetrics() {
        DisplayMetrics metric = getApplicationContext().getResources().getDisplayMetrics();
        mScreenWidth = metric.widthPixels;
        mScreenHeight = metric.heightPixels;
        mScreenDensity = metric.density;
        mScaledDensity = metric.scaledDensity;
    }

    public DisplayImageOptions initOptions(int resId) {
        BitmapFactory.Options decodingOptions = new BitmapFactory.Options();
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        builder
                .cacheInMemory(true).cacheOnDisc(true)
//                .displayer(new FadeInBitmapDisplayer(300))
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageForEmptyUri(resId).showImageOnFail(resId)
                .showImageOnLoading(resId)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .decodingOptions(decodingOptions)
                .displayer(DefaultConfigurationFactory.createBitmapDisplayer());
        return builder.build();
    }

    public DisplayImageOptions initOptions(int loadingImage, int errorImage) {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        builder.cacheInMemory(false).cacheOnDisc(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .displayer(new SimpleBitmapDisplayer())
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageForEmptyUri(errorImage).showImageOnFail(errorImage)
                .showImageOnLoading(loadingImage)
                .displayer(DefaultConfigurationFactory.createBitmapDisplayer());
        return builder.build();
    }


    public static CampusInnApp getInstance() {
        return instance;
    }

    public void initDbutils() {
//        CampusInnAppDb.getInstance().getSqlDateBase();

        dbUtils = DbUtils.create(this, Constants.DB_VERSION_NAME,
                Constants.DB_VERSION_CODE, new DbUtils.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbUtils dbUtils, int oldVersion,
                                          int newVersion) {
                    }
                });
        dbUtils.configAllowTransaction(true);

    }

//    /**
//     * 初始化程序字体
//     */
//    private void initFonts() {
//        mFontTypefaceLight = Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Light.otf");
//        mFontTypefaceMedium = Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Medium.otf");
//        mFontTypefaceNormal = Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Normal.otf");
//
//    }


    /**
     * 获取状态栏高度
     */
    public int getStatusBarHeight() {
        // 此代码不能在onCreate（）里面调用，否则获得高度为0
        // Rect frame = new Rect();
        // getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        // return frame.top;
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sbar;
    }

    /**
     * 添加Activity到容器中 *
     */
    public void addActivity(Activity activity) {

        if (activitys != null && activitys.size() > 0) {
            if (!activitys.contains(activity)) {
                activitys.add(activity);
            }
        } else {
            activitys.add(activity);
        }
    }

    /**
     * 遍历所有Activity并finish（用于最后退出应用） *
     */
    public void exit() {
        if (activitys != null && activitys.size() > 0) {
            for (Activity activity : activitys) {
                activity.finish();
            }
        }
         System.exit(0);
    }

    /**
     * 如果传入activity在容器中已经存在，则返回true，否则返回false。 *
     */
    public static boolean isExist(Object object) {
        for (int i = 0; i < activitys.size(); i++) {
            if (activitys.get(i).getClass().equals(object)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 如果传入activity在容器中已经添加，则关闭。 *
     */
    public void finishActivity(Object object) {
        for (int i = 0; i < activitys.size(); i++) {
            if (activitys.get(i) != null) {
                if (activitys.get(i).getClass().equals(object)) {
                    activitys.get(i).finish();
                }
            }

        }
    }

}
